const { Service } = require('egg')
const cheerio = require('cheerio')
const fs = require('fs')
const path = require('path')
const AipOcrClient = require('baidu-aip-sdk').ocr
const { RSAUtils } = require('../utils/RSA')

// 设置APPID/AK/SK
const APP_ID = '20636887'
const API_KEY = 'ZRSVur0vlzuGdv43WKfHfGHe'
const SECRET_KEY = 'VChEpLKDfHZy98EigC7v2nRGQiYGGjmp'

// const APP_ID = '63137349';
// const API_KEY = 'mLESDHq2EZWZCGoaRGxyC9J3';
// const SECRET_KEY = 'oGRAStfdI1NxvWJP5V3ZnNcjgEVm308H';

// 新建一个对象，建议只保存一个对象调用服务接口
const OcrClient = new AipOcrClient(APP_ID, API_KEY, SECRET_KEY)

const getCode = async (ctx, loginCookie) => {
  const verifyUrl = `${ctx.state.baseUrl}/cas/kaptcha?time=${new Date().getTime()}`
  const verifycodeRes = await ctx.curl(verifyUrl, {
    method: 'GET',
    headers: {
      'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      Cookie: loginCookie,
      Host: ctx.state.baseUrl.replace('https://', ''),
      Referer: verifyUrl,
    },
    timeout: 5000,
    rejectUnauthorized: false, // 忽略证书验证
  })

  // 保存到本地的文件路径
  const savePath = path.join(__dirname, `../public/${new Date().getTime()}.jpg`)
  // 将接收到的Buffer写入文件
  fs.writeFileSync(savePath, verifycodeRes.data)

  const imageBase64 = `data:image/jpeg;base64,${verifycodeRes.data.toString('base64')}`
  const result = await OcrClient.generalBasic(imageBase64)
  const code = result.words_result[0].words.toLowerCase().replace(/\s/g, '')
  return code
}

module.exports = class LoginService extends Service {
  /**
   * * 模拟登录，获取cookie
   * @return {setCookie: string, status: number} **
   */
  async getCookie() {
    try {
      const { ctx } = this
      const { sid, pwd } = ctx.data
      let cookie = ''

      /*  0. 请求主页获取登录所需参数 */
      const homeUrl = `${ctx.state.baseUrl}/cas/login?service=https://webvpn.zjjs.edu.cn/auth/cas_validate?entry_id=1`
      const homeRes = await ctx.curl(homeUrl, {
        method: 'GET',
        headers: {
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
        },
        rejectUnauthorized: false, // 忽略证书验证
      })
      const homeCookie = homeRes.headers['set-cookie'] ? homeRes.headers['set-cookie'].map((e) => e.split(';')[0]).join(';') : ''
      console.log('homeCookie', homeCookie)
      const homeDom = cheerio.load(homeRes.data.toString())
      const execution = homeDom('input[type="hidden"][name="execution"]').first().attr('value')
      const _eventId = homeDom('input[type="hidden"][name="_eventId"]').first().attr('value')
      const v = homeDom('head script[type="text/javascript"]').last().attr('src')
      /* end */

      /* 1. 获取新cookie */
      const temRes = await ctx.curl(`${ctx.state.baseUrl}/cas/${v}`, {
        method: 'GET',
        headers: {
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
          Cookie: homeCookie,
        },
        rejectUnauthorized: false, // 忽略证书验证
      })
      const loginCookie = temRes.headers['set-cookie'] ? temRes.headers['set-cookie'].map((e) => e.split(';')[0]).join(';') : ''
      cookie += loginCookie
      console.log('loginCookie', loginCookie)
      /* end */

      const authcode = await getCode(ctx, loginCookie) // 获取验证码
      console.log('authcode', authcode)

      /* 1. 请求加密密钥 */
      const keyUrl = `${ctx.state.baseUrl}/cas/v2/getPubKey?sf_request_type=ajax`
      const keyRes = await ctx.curl(keyUrl, {
        method: 'GET',
        headers: {
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
          Cookie: homeCookie,
        },
        rejectUnauthorized: false, // 忽略证书验证
      })
      const keyCookie = keyRes.headers['set-cookie'] ? keyRes.headers['set-cookie'].map((e) => e.split(';')[0]).join(';') : ''
      console.log('keyCookie', keyCookie)
      cookie += `;${keyCookie}`
      const publickey = JSON.parse(keyRes.data.toString())
      console.log('publickey', publickey)
      /* end */

      /* 密码加密 */
      // eslint-disable-next-line new-cap
      const key = new RSAUtils.getKeyPair(publickey.exponent, '', publickey.modulus)
      const reversedPwd = pwd.split('').reverse().join('')
      const encrypedPwd = RSAUtils.encryptedString(key, reversedPwd)

      /* end */
      console.log('encrypedPwd', encrypedPwd)

      /* 2. 登录  */
      const loginUrl = `${ctx.state.baseUrl}/cas/login?service=https://webvpn.zjjs.edu.cn/auth/cas_validate?entry_id=1`
      const loginRes = await ctx.curl(loginUrl, {
        method: 'POST',
        headers: {
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
          Cookie: cookie,
          Host: ctx.state.baseUrl.replace('https://', ''),
          Origin: ctx.state.baseUrl,
          Referer: loginUrl,
        },
        data: {
          username: sid,
          password: encrypedPwd,
          authcode,
          execution,
          _eventId,
        },
        timeout: 5000,
        rejectUnauthorized: false, // 忽略证书验证
      })
      console.log('loginRes', loginRes.status, loginRes.data.toString())

      return { setCookie: homeCookie, status: homeRes.status }
    } catch (err) {
      console.log(err)
      return { setCookie: '', status: 500 }
    }
  }
}
